const fs = require("fs"); //文件系统模块
const nodeXlsx = require('node-xlsx')	//引用node-xlsx模块
const ex1 = nodeXlsx.parse("./key.xls")	//读取excel表格

/**
 * 一个数组的出现次数，返回一个对象
 * @param {array} arr 
 * @returns 
 */
function getRepeatNum(arr) {
    return arr.reduce(function (prev, next) {
        prev[next] = (prev[next] + 1) || 1;
        return prev;
    }, {});
}

let excel_content = ex1[1].data, temp = []; //第一个是数据内容    定义一个空数组
excel_content.forEach((itemData) => {
    itemData && itemData.length > 0 && itemData.forEach((item) => {
        if (!(/(https):\/\/([\w.]+\/?)\S*/.test(item))) {
            temp.push(item);
        }
    })
})

let result = getRepeatNum(temp);

function getObjKeyOrValue(arr,flag){
    let tempArr = [];
    if(flag === true){
        Object.keys(arr).map((item) => {
            tempArr.push(item);
        })
        return tempArr;
    }else{
        Object.values(arr).map((item) => {
            tempArr.push(item);
        })
        return tempArr;
    }
}
let key = getObjKeyOrValue(result,true);
let values = getObjKeyOrValue(result);

let failArr = [];
key.forEach((item, index) => {
    failArr.push([item, values[index]])
})

let data = [{
    name: "new",
    data: [
        [
            "关键词",
            "出现次数"
        ],
        ...failArr,
    ]
}]
var buffer = nodeXlsx.build(data);
fs.writeFile('a.xlsx', buffer, function (err) {
    if (err) {
        console.log("Write failed: " + err);
        return;
    }
    console.log("Write completed.");
});
